#include"mainform.h"
#include"base64.h"

MainForm::MainForm(QWidget *parent):QMainWindow(parent)
{
    db = QSqlDatabase::addDatabase("QSQLITE","mainform");
    db.setDatabaseName("./database");
    db.open();
    QTextCodec::setCodecForTr(QTextCodec::codecForName("utf-8"));
    QTextCodec::setCodecForCStrings(QTextCodec::codecForName("utf-8"));
    ui.setupUi(this);
    trayicon = new QSystemTrayIcon(this);
    trayicon->setIcon(QIcon("./images/red-monster-happy-icon.png"));
    trayicon->setToolTip("download");
    QMenu* trayiconmenu = new QMenu(this);
    QAction* quit = new QAction("&Quit",this);
    QAction* normal = new QAction("&Normal",this);
    connect(quit,SIGNAL(triggered()),this,SLOT(close()));
    connect(normal,SIGNAL(triggered()),this,SLOT(showNormal()));
    trayiconmenu->addAction(normal);
    trayiconmenu->addAction(quit);
    trayicon->setContextMenu(trayiconmenu);
    trayicon->show();
    connect(ui.downloadpush,SIGNAL(released()),this,SLOT(StartFile(void)));
//    downloadcontrol = new DownloadControl(this);
//    connect(downloadcontrol,SIGNAL(DownloadInfo(const QString& ,const int& ,const int&,const QString&)),
//            this,SLOT( GetDownloadInfo(const QString& ,const int& ,const int& ,const QString& )));
//    connect(downloadcontrol,SIGNAL(ChangeTodayTable()),this,SLOT(ShowTodayTable()));

    conf = new Configure(this);
    connect(conf,SIGNAL(ConfigChange(confinfo)),this,SLOT(GetConfigChange(confinfo)));
    connect(ui.configureaction,SIGNAL(triggered()),conf,SLOT(show()));
    confdata = GetDataInfo();
    if(confdata.savepath.isEmpty() || !QFile(confdata.savepath).exists())
    {
        confdata.savepath = qgetenv("HOME");
        execsql("update configure set savepath ='"+confdata.savepath+"'");
    }
    todaytable = new TableWidget(this);
    historytable = new TableWidget(this);
    todaytable->setTableType(TODAYTABLE);
    historytable->setTableType(HISTORYTABLE);
    todaytable->setColumnCount(5);
    historytable->setColumnCount(2);
    ui.downloadinfotab->insertTab(0,todaytable,tr("今日下载"));
    ui.downloadinfotab->insertTab(1,historytable,tr("历史下载"));
    QStringList todayheaderlist,historyheaderlist;
    todayheaderlist<<tr("文件名")<<tr("速度")<<tr("大小")<<tr("已下载")<<tr("目录");
    todaytable->setHorizontalHeaderLabels(todayheaderlist);
    historyheaderlist<<tr("文件名")<<tr("目录");
    historytable->setHorizontalHeaderLabels(historyheaderlist);
    connect(ui.downloadinfotab,SIGNAL(currentChanged(int)),this,SLOT(ShowTable(int)));
    ShowTodayTable();
}
MainForm::~MainForm()
{
    db.close();
    QSqlDatabase::removeDatabase("mainform");
}

void MainForm::ShowTodayTable(void)
{
   QString sql;
   sql="select * from downloadfileinfo where isfinish = '0'";
   QSqlQuery query = db.exec(sql);
   QSqlRecord record = db.record("downloadfileinfo");
   int row=0;
   while(query.next())
   {
       todaytable->setRowCount(row+1);
       QString filename = query.value(record.indexOf("filename")).toString();
       int size = query.value(record.indexOf("filesize")).toInt();
       int finishsize = query.value(record.indexOf("finishsize")).toInt();
       QFileInfo fileinfo(filename);
       QString dir = fileinfo.dir().canonicalPath();
       filename =fileinfo.fileName();
       float filesize  =float( size)/1024/1024;
       finishsize = int((finishsize/float(size))*100);
       QTableWidgetItem* item0 = new QTableWidgetItem(filename);
       QTableWidgetItem* item1 = new QTableWidgetItem("0 KB/S");
       QTableWidgetItem* item2 = new QTableWidgetItem(QString::number(filesize,'f',1)+"MB");
       QTableWidgetItem* item3 = new QTableWidgetItem(QString::number(finishsize)+"%");
       QTableWidgetItem* item4 = new QTableWidgetItem(dir);
       todaytable->setItem(row,0,item0);
       todaytable->setItem(row,1,item1);
       todaytable->setItem(row,2,item2);
       todaytable->setItem(row,3,item3);
       todaytable->setItem(row,4,item4);
       todaytable->setColumnWidth(0,ColumnWidth);
       todaytable->setColumnWidth(4,ColumnWidth);
       item1->setTextAlignment(Qt::AlignCenter);
       item2->setTextAlignment(Qt::AlignCenter);
       item3->setTextAlignment(Qt::AlignCenter);
       row++;
   }
}

void MainForm::ShowHistoryTable(void)
{
    QString sql;
    sql="select * from downloadfileinfo where isfinish = 1 ";
    QSqlQuery query = db.exec(sql);
    QSqlRecord record = db.record("downloadfileinfo");
    int row=0;
    while(query.next())
    {
        historytable->setRowCount(row+1);
        QString filename = query.value(record.indexOf("filename")).toString();
        QFileInfo fileinfo(filename);
        QString dir = fileinfo.dir().canonicalPath();
        filename =fileinfo.fileName();
        QTableWidgetItem* item0 = new QTableWidgetItem(filename);
        QTableWidgetItem* item1 = new QTableWidgetItem(dir);
        historytable->setItem(row,0,item0);
        historytable->setItem(row,1,item1);
        historytable->setColumnWidth(0,ColumnWidth);
        historytable->setColumnWidth(1,ColumnWidth);
        row++;
    }
}

void MainForm::ShowTable(int index)
{
    if(index == 0)
    {
       ShowTodayTable();
    }
    else if(index == 1)
    {
       ShowHistoryTable();
    }
}

void MainForm::GetConfigChange(const confinfo &confdata)
{
    this->confdata = confdata;
}

void MainForm::GetDownloadInfo(const QString& file,const int& Rate,const int& percent,const QString& path)
{
  // qDebug()<<(file+ QObject::tr(" 下载速度 ")+ QString::number(Rate)+QObject::tr(" KB/S ") + QObject::tr("  已下载 ") + QString::number(percent) + QObject::tr("%  保存路径 ") + path);
  // ShowTodayTable();
   QFileInfo fileinfo(file);
   int row = todaytable->rowCount();
   int col = todaytable->columnCount();

   for(int i = 0;i<row;i++)
       for(int j =0;j<col;j++)
       {
            if(todaytable->item(i,j)->text() == file && todaytable->item(i,col-1)->text() == path)
            {
               // todaytable
                qDebug()<<row<<"   "<<col<<"  "<<file;
                QTableWidgetItem* item1 = new QTableWidgetItem(QString::number(Rate)+"KB/S");
                QTableWidgetItem* item3 = new QTableWidgetItem(QString::number(percent)+"%");
                todaytable->setItem(i,1,item1);
                todaytable->setItem(i,3,item3);
                item1->setTextAlignment(Qt::AlignCenter);
                item3->setTextAlignment(Qt::AlignCenter);
                return ;
            }
       }
}

void MainForm::StartFile(void)
{
   //http://ttplayer.qianqian.com/download/ttpsetup_581-44059078.exe
//    connect(todaytable,SIGNAL(StopDownload(QString)),downloadcontrol,SLOT(StopDownload(QString)));
//    connect(todaytable,SIGNAL(ContinueDownload(QString)),downloadcontrol,SLOT(ContinueDownload(QString)));
//    downloadcontrol->SetSavePath(confdata.savepath);
//    downloadcontrol->StartFileDownload(ui.urlline->text(),confdata.pointcount);
        downloadcontrol = new DownloadControl(this);
        connect(downloadcontrol,SIGNAL(DownloadInfo(const QString& ,const int& ,const int&,const QString&)),
                this,SLOT( GetDownloadInfo(const QString& ,const int& ,const int& ,const QString& )));
        connect(downloadcontrol,SIGNAL(ChangeTodayTable()),this,SLOT(ShowTodayTable()));

        connect(todaytable,SIGNAL(StopDownload(QString)),downloadcontrol,SLOT(StopDownload(QString)));
        connect(todaytable,SIGNAL(ContinueDownload(QString)),downloadcontrol,SLOT(ContinueDownload(QString)));
        downloadcontrol->SetSavePath(confdata.savepath);
        downloadcontrol->Init(ui.urlline->text(),confdata.pointcount);
        processmap[ui.urlline->text()] = downloadcontrol;
        downloadcontrol->StartFileDownload(ui.urlline->text(),confdata.pointcount);

}

void MainForm::closeEvent( QCloseEvent *event)
{}

void MainForm::changeEvent ( QEvent * event )
{
    if(event->type()==QEvent::WindowStateChange && this->isMinimized())
    {
        hide();
        event->ignore();
    }
}

void MainForm::CreateDownloadfile(void)
{

}

void MainForm::show()
{
    QMainWindow::show();
}

int main(int argc, char **argv)
{
    QApplication app(argc, argv);
        //用阻塞的方式下载文件，完成后退出
    MainForm* mainform = new MainForm();
    mainform->show();
    app.exec();
    delete mainform;
    return 0;
}
